package com.pti.usermanager.service.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import com.pti.usermanager.dao.api.UserDao;
import com.pti.usermanager.dao.po.UserPo;
import com.pti.usermanager.enums.ConstantCode;
import com.pti.usermanager.enums.RedisConsts;
import com.pti.usermanager.service.api.LoginService;
import com.pti.usermanager.utils.KeyUtils;
import com.pti.usermanager.utils.RedisUtils;
import com.pti.usermanager.web.dto.response.ResultResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


/**
 * @ClassName: LoginServiceImpl
 * @Author: liumengyao
 * @Description:
 * @Date: 2019/2/18
 */
@Service
public class LoginServiceImpl implements LoginService {

    private static final Logger logger = LogManager.getLogger(LoginServiceImpl.class);

    @Autowired
    private UserDao userDao;
    @Autowired
    RedisUtils redisUtils;


    /**
     * @Author liumengyao
     * @Description 根据用户名查询确定登陆
     * @Date 2019/2/18
     */
    @Override
    public ResultResponse loginByLoginName(String loginNm, String usrPwd) {
        logger.debug("loginNm:{} usrPwd:{}",loginNm,usrPwd);
        ResultResponse resultResponse = new ResultResponse();

        if(StringUtils.isEmpty(loginNm) || StringUtils.isEmpty(usrPwd)){
            resultResponse.setCode(ConstantCode.DTO.LOGIN_ERROR_CODE);
            resultResponse.setMessage(ConstantCode.DTO.LOGIN_LOGINNM_ERROR);
            return resultResponse;
        }
        UserPo userByloginNm = userDao.findUserByloginNm(loginNm);
        if(userByloginNm == null){
            resultResponse.setCode(ConstantCode.DTO.LOGIN_ERROR_CODE);
            resultResponse.setMessage(ConstantCode.DTO.LOGINNM_NOT_EXITS);
            return resultResponse;
        }
        if(!userByloginNm.getUsrPwd().equals(usrPwd)){
            resultResponse.setCode(ConstantCode.DTO.LOGIN_ERROR_CODE);
            resultResponse.setMessage(ConstantCode.DTO.USRPWD_NOT_EXITS);
            return resultResponse;
        }
        //生成token并保存在Redis中
        String token = KeyUtils.genUniqueKey();
        //将token存储在 Redis 中。键是 TOKEN_用户id, 值是token
        redisUtils.setString(String.format(RedisConsts.TOKEN_TEMPLATE,userByloginNm.getUsrId()),token,2L,TimeUnit.HOURS);
        //将用户信息存放到redis中，用于common服务调用
        String userJson = JSON.toJSONString(userByloginNm);
        redisUtils.setString(String.valueOf(userByloginNm.getUsrId()),userJson,2L,TimeUnit.HOURS);
        resultResponse.setData(userByloginNm);
        resultResponse.setToken(token);
        return resultResponse;
    }
}
